#include "Circle.h"


Circle::Circle( ) : m_pBatchNode(0) , m_fRadius(0) , m_fSpeed(0)
{
	
}


Circle::~Circle( )
{
	if( m_pListSegment ){
		m_pListSegment->removeAllObjects( );
		m_pListSegment->release();
	}

	this->removeAllChildrenWithCleanup(true);
}



bool Circle::init( )
{
	if( !CCNode::init() )
		return false;

	m_pListSegment = new CCArray( );

	return true;
}


void Circle::addSegment( CircleSegment* pSegment , float angle )
{
	if( !m_pListSegment )
		return;

	m_pListSegment->addObject( pSegment );

	pSegment->setPosition(  ccp( m_fRadius * sinf( CC_DEGREES_TO_RADIANS( angle ) ) , m_fRadius * cosf( CC_DEGREES_TO_RADIANS( angle ) ) ) );

	if( m_pBatchNode ){
		m_pBatchNode->addChild( pSegment , m_pListSegment->count() , m_pListSegment->count() );
	}else{
		this->addChild( pSegment , m_pListSegment->count() , m_pListSegment->count() );
	}
}


void Circle::removeLastSegment( )
{
	if( m_pListSegment && m_pListSegment->count() > 0 ){
		CircleSegment* pSegment = (CircleSegment*)m_pListSegment->lastObject( );
		m_pListSegment->removeLastObject( );

		pSegment->setVisible(false);
		pSegment->setTag( SEGMENT_UN_ACTIVE );
	}
}


void Circle::removeSegment(CircleSegment* pSegment )
{
	if( m_pListSegment && m_pListSegment->count() > 0 ){
		if( pSegment == (CircleSegment*)m_pListSegment->objectAtIndex(0) ){
			m_pListSegment->removeObject(pSegment);

			pSegment->setVisible(false);
			pSegment->getPhysicObject()->setActive(false);
			pSegment->setTag( SEGMENT_UN_ACTIVE );

			if( m_pListSegment->count() == 0 ){
				//Kill it
				OrbitSystem* pOrbit = (OrbitSystem*)this->getParent();
				if( pOrbit ){
					pOrbit->removeCircle( this );
				}
			}
		}
	}
}



void Circle::setRadius( float radius )
{
	float oldRadius = m_fRadius;
	m_fRadius = radius ;

	CCObject* pObj = NULL;
	CCARRAY_FOREACH( m_pListSegment , pObj ){
		CircleSegment* pSegment = dynamic_cast<CircleSegment*>(pObj);
		if( pSegment ){
			if( oldRadius != 0 ){
				float sinAngleX = pSegment->getPositionX() / oldRadius;
				float cosAngleY = pSegment->getPositionY() / oldRadius;
				pSegment->setPosition(  ccp( m_fRadius * sinAngleX  , m_fRadius * cosAngleY  ) );
			}else{
				pSegment->setPosition( CCPointZero );
			}
		}
	}
}


void Circle::rotate( )
{
	this->runAction( CCRepeatForever::create( CCRotateBy::create( 1.0f , m_fSpeed ) ) );
}